<?php

namespace App\Services;

use App\Models\MemberModel;
use App\Models\RedPackLogModel;
use App\Utils\PriceUtis;
use Illuminate\Support\Facades\DB;

class RedPackService
{
    /**
     * 给用户增加红包
     * @param int $userId 用户id
     * @param int $redPack 红包数量，单位元
     * @param int $channelId 渠道
     * @param int $type 操作类型：1增加，2减少
     * @param int $relationId 关联id
     * @return mixed
     */
    public function addMemberRedPack(int $userId, int $redPack, int $channelId, int $type, int $relationId)
    {
        if ($channelId <= 0) {
            throw new \Exception('渠道异常');
        }
        if ($type <= 0) {
            throw new \Exception('操作类型异常');
        }
        DB::transaction(function () use ($userId, $redPack, $channelId, $type, $relationId) {
            // 修改账户红包余额
            $memberModel = new MemberModel();
            $userInfo = $memberModel->where([
                'id' => $userId
            ])->first();
            if ($type == 1) {
                // 增加
                $userInfo->red_pack += PriceUtis::toFen($redPack);
            } else {
                $userInfo->red_pack -= PriceUtis::toFen($redPack);
            }
            if ($userInfo->red_pack < 0) {
                throw new \Exception('用户余额修改失败');
            }
            $res = $userInfo->save();
            if (!$res) {
                throw new \Exception('用户余额修改失败');
            }

            // 记录日志
            $redPackProportion = (int) env('INTEGRAL_EXCHANGE_PROPORTION');
            $redPackLog = new RedPackLogModel();
            $redPackLog->user_id = $userId;
            $redPackLog->red_pack_num = PriceUtis::toFen($redPack);
            $redPackLog->channel = $channelId;
            $redPackLog->type = $type;
            $redPackLog->relation_id = $relationId;
            $redPackLog->current_proportion = $redPackProportion;
            $res = $redPackLog->save();
            if (!$res) {
                throw new \Exception('日志记录失败');
            }
        });
        return true;
    }

    /**
     * 积分兑换现金
     * @param int $userId 用户id
     * @param int $redPackNum 红包数量
     */
    public function exchangeMoney(int $userId, int $redPackNum)
    {
        // 红包金额比例
        $redPackProportion = (int) env('INTEGRAL_EXCHANGE_PROPORTION');
        $memberService = new MemberService();
        try {
            $res = $this->addMemberRedPack($userId, $redPackNum, 3, 2, 0);
            if ($res) {
                $memberService->editBoolean(1, $userId, bcdiv($redPackNum, $redPackProportion, 4));
                return [true, '成功'];
            }
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
        }
    }
}
